package com.xbongbong.saas.service.toolbox.help;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.elasticsearch.model.PaasFormDataEsModel;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.sys.help.PackageHelp;
import com.xbongbong.paas.model.BusinessRuleInfoModel;
import com.xbongbong.paas.model.PaasAppModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.model.PaasProcessTemplateModel;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisConstant;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.pro.constant.BasePackageConstant;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.enums.PackageStatusEnum;
import com.xbongbong.pro.enums.PackageTypeEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.SaasTableCountTypeEnum;
import com.xbongbong.pro.enums.ValueAddedTypeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.packageInfo.pojo.vo.BasePackageInfoVO;
import com.xbongbong.pro.statistic.enums.ChartTypeEnum;
import com.xbongbong.pro.statistic.enums.StatisticsTypeEnum;
import com.xbongbong.pro.statistic.model.ChartCustomModel;
import com.xbongbong.pro.statistic.model.DataSetModel;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.enums.SheetAloneEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.PaymentEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.model.AiAssistantModel;
import com.xbongbong.saas.model.CabinetFileModel;
import com.xbongbong.saas.model.DistributorAccountModel;
import com.xbongbong.saas.model.HomePageManageModel;
import com.xbongbong.saas.model.IndexTypeModel;
import com.xbongbong.sys.domain.entity.FeeLogEntity;
import com.xbongbong.sys.model.FeeLogModel;
import com.xbongbong.workflow.model.WorkflowTaskLogModel;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * 套餐校验帮助类
 * 创建时间 2019/7/4 4:37 PM
 * 修改时间 2019/7/4 4:37 PM
 * @author chy
 * @since v1.0
 * @version v1.0
 */
@Component
public class UpdatePackageRedisHelp {

    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private FeeLogModel feeLogModel;
    @Resource
    private PackageHelp packageHelp;
    @Resource
    private PaasFormDataEsModel paasFormDataEsModel;
    @Resource
    private IndexTypeModel indexTypeModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private CabinetFileModel cabinetFileModel;
    @Resource
    private PaasProcessTemplateModel paasProcessTemplateModel;
    @Resource
    private ChartCustomModel chartCustomModel;
    @Resource
    private PaasAppModel paasAppModel;
    @Resource
    private AiAssistantModel aiAssistantModel;
    @Resource
    private BusinessRuleInfoModel businessRuleInfoModel;
    @Resource
    private DistributorAccountModel distributorAccountModel;
    @Resource
    private WorkflowTaskLogModel workflowTaskLogModel;
    @Resource
    private HomePageManageModel homePageManageModel;
    @Resource
    private DataSetModel dataSetModel;


    /**
     * 更新缓存套餐信息
     * @param corpid
     * @param valueAddedTypeEnum
     * @return
     * @throws XbbException
     * 创建时间 2019/7/4 5:33 PM
     * 修改时间 2019/7/4 5:33 PM
     * @author chy
     * @since v1.0
     * @version v1.0
     */
    public JSONObject updatePaasPackage2Redis(String corpid, ValueAddedTypeEnum valueAddedTypeEnum, XbbRefTypeEnum xbbRefTypeEnum, Long formId) throws XbbException {

        if (valueAddedTypeEnum == ValueAddedTypeEnum.TOTAL_FORM_DATA_NUM
                || valueAddedTypeEnum == ValueAddedTypeEnum.ONE_FORM_DATA_NUM) {
            //表单数据量走特殊逻辑
            return updateSpecialPaasPackage2Redis(corpid, valueAddedTypeEnum, xbbRefTypeEnum, formId);
        }

        JSONObject valueAdded = getValueAdded(corpid, valueAddedTypeEnum);

        Integer type = valueAddedTypeEnum.getType();

        JSONObject packageRet = null;

        //当不存在数据库配置的时候，应该在缓存中塞入一个不可用的，可以减少数据库查询
        if (valueAdded == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018);
        }
        switch (valueAddedTypeEnum){
            case CUSTOM_FORM_NUM :
                packageRet = customFormNum4Redis(corpid, valueAdded);
                break;
            case CAPACITY_NUM:
                packageRet = capacityNum4Redis(corpid, valueAdded);
                break;
            case CUSTOM_PROCESS_NUM:
                packageRet = customProcessNum4Redis(corpid, valueAdded);
                break;
            case CUSTOM_CHART_NUM:
                packageRet = customChartNum4Redis(corpid, valueAdded);
                break;
            case CUSTOM_APPLICATION_NUM:
                packageRet = customApplicationNum4Redis(corpid, valueAdded);
                break;
            case AI_ASSISTANT:
                packageRet = aiAssistantNum4Redis(corpid, valueAdded);
                break;
            case API:
                packageRet = api4Redis(corpid, valueAdded);
                break;
            case BUSINESS_RULES:
                packageRet = businessRules4Redis(corpid, valueAdded);
                break;
            case DISTRIBUTOR:
                packageRet = distributor4Redis(corpid, valueAdded);
                break;
            case WORKFLOW:
                packageRet = workflow4Redis(corpid, valueAdded);
                break;
            case HOME_PAGE:
                packageRet = homePageNum4Redis(corpid, valueAdded);
                break;
            case DATA_SET:
                packageRet = dataSetNum4Redis(corpid, valueAdded);
                break;
            case WORK_ORDER_V2:
                packageRet = workOrderV2Redis(corpid, valueAdded);
                break;
            default:
                break;
        }
        paasRedisHelper.setValue(RedisPrefixConstant.VALUE_ADDED, corpid + "_" + type, packageRet, RedisConstant.TINY_DURATION);
        return packageRet;
    }

    /**
     * 自定义表单数（类型数）
     * @param corpid
     * @param valueAdded {"alias":"customFormNum","name":"自定义表单", "type":3, "value":1}
     * @return {"totalValue":0,"usedValue":0,"status":0 }
     * 创建时间 2019/4/15 9:17 AM
     * 修改时间 2019/4/15 9:17 AM
     * @author chy
     * @since v1.0
     * @version v1.0
     */
    private JSONObject customFormNum4Redis(String corpid, JSONObject valueAdded) {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("saasMark", SaasMarkEnum.PAAS.getCode());
        param.put("del", 0);
        Integer count = paasFormModel.getEntitysCount(param);

        Integer primaryNum = valueAdded.getInteger("value");

        Integer status = getPackageStatus(primaryNum, count);

        return packageJson(primaryNum, count, status);
    }


    /**
     * 通过数据库配置生成云容量限制存入redis的配置,此配置仅用到primaryNum
     * @param corpid 公司id
     * @param valueAdded {"alias":"capacityNum","name":"存储容量", "type":6, "value":200}
     * @return {"totalValue":2, "usedValue":1, "status":1} totalValue、usedValue单位为MB
     * 创建时间 2019/3/26 7:18 PM
     * 修改时间 2019/3/26 7:18 PM
     * @author chy
     * @since v1.0
     * @version v1.0
     */
    private JSONObject capacityNum4Redis(String corpid, JSONObject valueAdded){

        Long size = cabinetFileModel.getAllSizeByCorpid(corpid);

        size = size == null ? 0 : size;

        Long sizeMb = size/1024/1024;

        Integer sizeIntMb = sizeMb.intValue();

        Integer totalValue = valueAdded.getInteger("value");

        Integer totalValueMb = totalValue * 1024;

        Integer status = getPackageStatus(totalValueMb, sizeIntMb);

        return packageJson(totalValueMb, sizeIntMb, status);
    }

    /**
     * 通过数据库配置生成自定义流程数量限制存入redis的配置
     * @param corpid 公司id
     * @param valueAdded {"alias":"customProcessNum","name":"自定义流程", "type":7, "value":5}
     * @return
     * 创建时间 2019/4/15 10:00 AM
     * 修改时间 2019/4/15 10:00 AM
     * @author chy
     * @since v1.0
     * @version v1.0
     */
    private JSONObject customProcessNum4Redis(String corpid, JSONObject valueAdded) {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("saasMark", SaasMarkEnum.PAAS.getCode());
        param.put("del", 0);
        Integer count = paasProcessTemplateModel.getEntitysCount(param);

        Integer primaryNum = valueAdded.getInteger("value");
        Integer status = getPackageStatus(primaryNum, count);

        return packageJson(primaryNum, count, status);
    }

    /**
     * 获取公司自定义图表限制信息
     * @param corpid 公司id
     * @param valueAdded {"alias":"customChartNum","name":"自定义图表数量", "type":9, "value":5}
     * @return
     * 创建时间 2019/4/15 10:12 AM
     * 修改时间 2019/4/15 10:12 AM
     * @author chy
     * @since v1.0
     * @version v1.0
     */
    private JSONObject customChartNum4Redis(String corpid, JSONObject valueAdded) {

        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("statisticsType", StatisticsTypeEnum.CUSTOM_STATISTIC.getCode());
        param.put("chartTypeExclude", ChartTypeEnum.VALUE.getCode());
        param.put("del", 0);
        Integer count = chartCustomModel.getEntitysCount(param);
        Integer primaryNum = valueAdded.getInteger("value");
        Integer status = getPackageStatus(primaryNum, count);
        return packageJson(primaryNum, count, status);
    }


    /**
     * 通过数据库配置生成自定义应用数量限制存入redis的配置
     * @param corpid 公司id
     * @param valueAdded {"alias":"customApplicationNum","name":"自定义应用数量", "type":8, "value":10}
     * @return
     * 创建时间 2019/3/26 7:31 PM
     * 修改时间 2019/3/26 7:31 PM
     * @author chy
     * @since v1.0
     * @version v1.0
     */
    private JSONObject customApplicationNum4Redis(String corpid, JSONObject valueAdded){
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("saasMark", SaasMarkEnum.PAAS.getCode());
        param.put("del", 0);
        Integer count = paasAppModel.getEntitysCount(param);
        Integer primaryNum = valueAdded.getInteger("value");
        Integer status = getPackageStatus(primaryNum, count);
        return packageJson(primaryNum, count, status);
    }

    /**
     * 通过数据库配置生成总表单限制存入redis的配置,此配置仅用到primaryNum
     * @param corpid 公司id
     * @param valueAdded {"alias":"sfaNum","name":"智能助手", "type":11, "value":20}
     * @return {"totalValue":0,"usedValue":0,"status":0 }
     * 创建时间 2019/3/26 4:28 PM
     * 修改时间 2019/3/26 4:28 PM
     * @author chy
     * @since v1.0
     * @version v1.0
     */
    private JSONObject aiAssistantNum4Redis(String corpid, JSONObject valueAdded){
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("enable", BasicConstant.ONE);
        param.put("del", 0);
        Integer count = aiAssistantModel.getEntitysCount(param);
        Integer totalValue = valueAdded.getInteger("value");
        Integer status = getPackageStatus(totalValue, count);
        return packageJson(totalValue, count, status);
    }

    private JSONObject api4Redis(String corpid, JSONObject valueAdded) {
        Integer primaryNum = valueAdded.getInteger("value");
        Integer status = getPackageStatus(primaryNum, 1);
        return packageJson(primaryNum, 1, status);
    }

    /**
     * 业务规则
     * @param corpid
     * @param valueAdded
     * @return
     */
    private JSONObject businessRules4Redis(String corpid, JSONObject valueAdded) {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("del", 0);
        Integer count = businessRuleInfoModel.getEntitysCount(param);
        Integer primaryNum = valueAdded.getInteger("value");
        Integer status = getPackageStatus(primaryNum, count);
        return packageJson(primaryNum, count, status);
    }

    /**
     * 经销商席位数
     * @param corpid
     * @param valueAdded
     * @return
     */
    private JSONObject distributor4Redis(String corpid, JSONObject valueAdded) {
        Integer count = distributorAccountModel.getDistributorAccountNum(corpid).size();
        Integer primaryNum = valueAdded.getInteger("value");
        Integer status = getPackageStatus(primaryNum, count);

        return packageJson(primaryNum, count, status);
    }

    /**
     *  工作流
     * @param corpid
     * @param valueAdded
     * @return
     */
    private JSONObject workflow4Redis(String corpid, JSONObject valueAdded) {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("del", 0);
        param.put("addTimeStart", DateTimeUtil.getFirstDateOfThisMonth());
        param.put("addTimeEnd", DateTimeUtil.getInt());
        Integer count = workflowTaskLogModel.getEntitysCount(param);
        Integer primaryNum = valueAdded.getInteger("value");
        Integer status = getPackageStatus(primaryNum, count);
        return packageJson(primaryNum, count, status);
    }

    /**
     * 通过数据库配置生成总表单限制存入redis的配置,此配置仅用到primaryNum
     * @param corpid 公司id
     * @param valueAdded {"alias":"sfaNum","name":"智能助手", "type":11, "value":20}
     * @return {"totalValue":0,"usedValue":0,"status":0 }
     * 创建时间 2019/3/26 4:28 PM
     * 修改时间 2019/3/26 4:28 PM
     * @author chy
     * @since v1.0
     * @version v1.0
     */
    private JSONObject homePageNum4Redis(String corpid, JSONObject valueAdded){
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("del", 0);
        Integer count = homePageManageModel.getEntitysCount(param);
        Integer totalValue = valueAdded.getInteger("value");
        Integer status = getPackageStatus(totalValue, count);
        return packageJson(totalValue, count, status);
    }
    /**
     * 通过数据库配置生成总表单限制存入redis的配置,此配置仅用到primaryNum
     * @param corpid 公司id
     * @param valueAdded {"alias":"sfaNum","name":"智能助手", "type":11, "value":20}
     * @return {"totalValue":0,"usedValue":0,"status":0 }
     * 创建时间 2019/3/26 4:28 PM
     * 修改时间 2019/3/26 4:28 PM
     * @author chy
     * @since v1.0
     * @version v1.0
     */
    private JSONObject workOrderV2Redis(String corpid, JSONObject valueAdded){
        Boolean pastDue;
        try {
            pastDue = feeLogModel.workOrderV2PastDue(corpid);
        } catch (XbbException e) {
            pastDue = false;
        }
        Integer primaryNum = valueAdded.getInteger("value");
        Integer status = getPackageStatus(primaryNum, 1);
        return packageJson(primaryNum, pastDue ? 1 : 0, status);
    }

    /**
     * 更新特殊的增值套餐
     * @param corpid
     * @param valueAddedTypeEnum
     * @param xbbRefTypeEnum 指定saas业务的单表数据量时，需要传 参照 {@link com.xbongbong.pro.enums.SaasTableCountTypeEnum}
     * @param formId 自定义表单的单表数据量时，需要传
     * @return
     * @throws XbbException
     * 创建时间 2019/7/4 5:34 PM
     * 修改时间 2019/7/4 5:34 PM
     * @author chy
     * @since v1.0
     * @version v1.0
     */
    @Async(value = "updateSpecialPaasPackage2RedisThreadPool")
    public JSONObject updateSpecialPaasPackage2Redis(String corpid, ValueAddedTypeEnum valueAddedTypeEnum, XbbRefTypeEnum xbbRefTypeEnum, Long formId) throws XbbException {
        JSONObject valueAdded = getValueAdded(corpid, valueAddedTypeEnum);
        Integer type = valueAddedTypeEnum.getType();
        JSONObject packageRet = new JSONObject();
        //当不存在数据库配置的时候，应该在缓存中塞入一个不可用的，可以减少数据库查询
        if (valueAdded == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, "数据错误，更新缓存失败");
        }
        switch (valueAddedTypeEnum){
            case TOTAL_FORM_DATA_NUM:
                packageRet = allFormNum4Redis(corpid, valueAdded);
                break;
            case ONE_FORM_DATA_NUM:
                packageRet = oneFormNum4Redis(corpid, valueAdded, xbbRefTypeEnum, formId);
                break;
            default:
                break;
        }
        Long effectiveTime = DateTimeUtil.getInt() + (RedisConstant.TINY_DURATION * 5L);
        //当redis时间超过5分钟，刷新redis的值
        packageRet.put("effectiveTime", effectiveTime);
        String key = corpid + "_" + type;
        //redis的有效时间设为半小时，此处和下面的有效时间相差不大，会使用户感受到算的过程。
        if (Objects.equals(valueAddedTypeEnum, ValueAddedTypeEnum.ONE_FORM_DATA_NUM)) {
            if (SaasTableCountTypeEnum.isSaasData(xbbRefTypeEnum)) {
                key += "_" + xbbRefTypeEnum.getCode();
            } else if (Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.SYSTEM)
                    || Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.PAAS)) {
                key += "_" + xbbRefTypeEnum.getCode() + "_" + formId;
            }
            paasRedisHelper.setValue(RedisPrefixConstant.VALUE_ADDED,
                    key, packageRet, RedisConstant.SHORTER_DURATION);
        } else {
            paasRedisHelper.setValue(RedisPrefixConstant.VALUE_ADDED,
                    key, packageRet, RedisConstant.SHORTER_DURATION);
        }
        return packageRet;
    }
    /**
     * 获取指定的增值业务配置
     * @param corpid
     * @param valueAddedTypeEnum
     * @return {"alias":"customFormNum","name":"自定义应用数量套餐", "type":3, "value":5}
     * 创建时间 2019/3/25 7:30 PM
     * 修改时间 2019/3/25 7:30 PM
     * @author chy
     * @since v1.0
     * @version v1.0
     */
    public JSONObject getValueAdded(String corpid, ValueAddedTypeEnum valueAddedTypeEnum) throws XbbException {
        JSONObject valueAdded = new JSONObject();

        Integer basePackageType = packageHelp.getFeeType(corpid);
        switch (valueAddedTypeEnum) {
            case CUSTOM_FORM_NUM :
                Integer baseCustomFormNum = getBaseCustomFormNum(basePackageType);
                Integer totalCustomFormNum = baseCustomFormNum +
                        getBuyValueFromFeeLog(corpid, PackageTypeEnum.CUSTOM_FORM_NUM.getType());
                valueAdded = formatValueAdded(valueAddedTypeEnum, totalCustomFormNum);
                break;
            case TOTAL_FORM_DATA_NUM:
                Double baseTotalFormDataNum = getBaseTotalFormDataNum(basePackageType);
                Double totalFormDataNum = baseTotalFormDataNum +
                        getBuyValueFromFeeLog(corpid, PackageTypeEnum.FORM.getType());
                valueAdded = formatValueAdded(valueAddedTypeEnum, totalFormDataNum);
                break;
            case ONE_FORM_DATA_NUM:
                Double baseOneFormDataNum = getBaseOneFormDataNum(basePackageType);
                Double oneFormDataNum = baseOneFormDataNum +
                        getBuyValueFromFeeLog(corpid, PackageTypeEnum.FORM.getType());
                valueAdded = formatValueAdded(valueAddedTypeEnum, oneFormDataNum);
                break;
            case CAPACITY_NUM:
                Integer baseCapacityNum = getBaseCapacityNum(basePackageType);
                Integer capacityNum = baseCapacityNum +
                        getBuyValueFromFeeLog(corpid, PackageTypeEnum.CAPACITY.getType());
                valueAdded = formatValueAdded(valueAddedTypeEnum, capacityNum);
                break;
            case CUSTOM_PROCESS_NUM:
                Integer baseCustomFlowNum = getBaseCustomFlowNum(basePackageType);
                valueAdded = formatValueAdded(valueAddedTypeEnum, baseCustomFlowNum);
                break;
            case CUSTOM_CHART_NUM:
                Integer baseCustomChartNum = getBaseCustomChartNum(basePackageType);
                // 加个特殊逻辑，在2021年11月19号零点之前的高级版套餐是20个图表
                if (Objects.equals(basePackageType,PackageTypeEnum.ADVANCED.getType())){
                    BasePackageInfoVO basePackageInfoVO = packageHelp.getBasePackageInfoFromRedis(corpid);
                    Long feeStartTime = basePackageInfoVO.getFeeStartTime();
                    Long specialTime = 1637251200L;
                    if (null != feeStartTime && feeStartTime < specialTime){
                        baseCustomChartNum = 20;
                    }
                }
                Integer customChartNum = baseCustomChartNum +
                        getBuyValueFromFeeLog(corpid, PackageTypeEnum.CUSTOM_CHART_NUM.getType());
                valueAdded = formatValueAdded(valueAddedTypeEnum, customChartNum);
                break;
            case CUSTOM_APPLICATION_NUM:
                Integer baseCustomApplicationNum = getBaseCustomApplicationNum(basePackageType);
                valueAdded = formatValueAdded(valueAddedTypeEnum, baseCustomApplicationNum);
                break;
            case AI_ASSISTANT:
                Integer baseSfaNum = getBaseSfaNum(basePackageType);
                Integer sfaNum = baseSfaNum +
                        getBuyValueFromFeeLog(corpid, PackageTypeEnum.AI_ASSISTANT.getType());
                valueAdded = formatValueAdded(valueAddedTypeEnum, sfaNum);
                break;
            case API:
                Integer baseApiNum = getBaseApiNum(basePackageType);
                Integer apiNum = baseApiNum +
                        getBuyValueFromFeeLog(corpid, PackageTypeEnum.API.getType());
                valueAdded = formatValueAdded(valueAddedTypeEnum, apiNum);
                break;
            case BUSINESS_RULES:
                Integer baseBusinessRulesNum = getBaseBusinessRulesNum(basePackageType);
                Integer businessRulesNum = baseBusinessRulesNum +
                        getBuyValueFromFeeLog(corpid, PackageTypeEnum.BUSINESS_RULES.getType());
                valueAdded = formatValueAdded(valueAddedTypeEnum, businessRulesNum);
                break;
            case DISTRIBUTOR:
                Integer distributorNum = getBuyValueFromFeeLog(corpid, PackageTypeEnum.DISTRIBUTOR.getType());
                valueAdded = formatValueAdded(valueAddedTypeEnum, distributorNum);
                break;
            case WORKFLOW:
                Integer baseWorkflowNum = getBaseWorkflowNum(basePackageType);
                Integer workflowNum = baseWorkflowNum +
                        getBuyValueFromFeeLog(corpid, PackageTypeEnum.WORKFLOW.getType());
                valueAdded = formatValueAdded(valueAddedTypeEnum, workflowNum);
                break;
            case HOME_PAGE:
                Integer baseHomePageNum = getBaseHomePageNum(basePackageType);
                Integer homePageNum = baseHomePageNum +
                        getBuyValueFromFeeLog(corpid, PackageTypeEnum.HOME_PAGE.getType());
                valueAdded = formatValueAdded(valueAddedTypeEnum, homePageNum);
                break;
            case DATA_SET:
                Integer baseDataSetNum = getBaseDataSetNum(basePackageType);
                Integer dataSetNum = baseDataSetNum +
                        getBuyValueFromFeeLog(corpid, PackageTypeEnum.DATA_SET.getType());
                valueAdded = formatValueAdded(valueAddedTypeEnum, dataSetNum);
                break;
            case WORK_ORDER_V2:
                Integer baseWorkOrderV2Num = getBaseHomePageNum(basePackageType);
                Integer workOrderV2Num = baseWorkOrderV2Num +
                        getBuyValueFromFeeLog(corpid, PackageTypeEnum.WORK_ORDER_V2.getType());
                valueAdded = formatValueAdded(valueAddedTypeEnum, workOrderV2Num);
                break;
            default:
                break;
        }

        return valueAdded;
    }

    private Integer getBuyValueFromFeeLog(String corpid, Integer type) {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("nowTime", DateTimeUtil.getInt());
        param.put("feeType", type);
        param.put("del", 0);
        Integer buyValue = 0;
        List<FeeLogEntity> list = feeLogModel.findEntitys(param);
        for (FeeLogEntity feeLog : list) {
            Integer isPay = feeLog.getIsPay();
            Integer sumValue = Math.abs(feeLog.getSumValue());
            if (Objects.equals(isPay, 0) || Objects.equals(isPay, 2)) {
                continue;
            }
            if (Objects.equals(isPay, 1)) {
                buyValue += sumValue;
            }
        }
        return buyValue;
    }

    /**
     * 获取自定义表单数
     * @param basePackageType 基础套餐类型
     * @return
     */
    private Integer getBaseCustomFormNum(Integer basePackageType) {
        Integer baseCustomFormNum = 0;
        PackageTypeEnum packageTypeEnum = PackageTypeEnum.getByType(basePackageType);
        switch (packageTypeEnum) {
            case FREE:
                baseCustomFormNum = BasePackageConstant.FreePackage.CUSTOM_FORM_NUM;
                break;
            case STANDARD:
                baseCustomFormNum = BasePackageConstant.StandardPackage.CUSTOM_FORM_NUM;
                break;
            case ADVANCED:
                baseCustomFormNum = BasePackageConstant.AdvancedPackage.CUSTOM_FORM_NUM;
                break;
            case ULTIMATE:
                baseCustomFormNum = BasePackageConstant.UltimatePackage.CUSTOM_FORM_NUM;
                break;
            default:
                break;
        }
        return baseCustomFormNum;
    }

    /**
     * 获取总表单数据量
     * @param basePackageType 基础套餐类型
     * @return
     */
    private Double getBaseTotalFormDataNum(Integer basePackageType) {
        Double baseTotalFormDataNum = 0.0;
        PackageTypeEnum packageTypeEnum = PackageTypeEnum.getByType(basePackageType);
        switch (packageTypeEnum) {
            case FREE:
                baseTotalFormDataNum = BasePackageConstant.FreePackage.TOTAL_FORM_DATA_NUM;
                break;
            case STANDARD:
                baseTotalFormDataNum = BasePackageConstant.StandardPackage.TOTAL_FORM_DATA_NUM;
                break;
            case ADVANCED:
                baseTotalFormDataNum = BasePackageConstant.AdvancedPackage.TOTAL_FORM_DATA_NUM;
                break;
            case ULTIMATE:
                baseTotalFormDataNum = BasePackageConstant.UltimatePackage.TOTAL_FORM_DATA_NUM;
                break;
            default:
                break;
        }
        return baseTotalFormDataNum;
    }

    /**
     * 获取单表单数据量
     * @param basePackageType 基础套餐类型
     * @return
     */
    private Double getBaseOneFormDataNum(Integer basePackageType) {
        Double baseOneFormDataNum = 0.0;
        PackageTypeEnum packageTypeEnum = PackageTypeEnum.getByType(basePackageType);
        switch (packageTypeEnum) {
            case FREE:
                baseOneFormDataNum = BasePackageConstant.FreePackage.ONE_FORM_DATA_NUM;
                break;
            case STANDARD:
                baseOneFormDataNum = BasePackageConstant.StandardPackage.ONE_FORM_DATA_NUM;
                break;
            case ADVANCED:
                baseOneFormDataNum = BasePackageConstant.AdvancedPackage.ONE_FORM_DATA_NUM;
                break;
            case ULTIMATE:
                baseOneFormDataNum = BasePackageConstant.UltimatePackage.ONE_FORM_DATA_NUM;
                break;
            default:
                break;
        }
        return baseOneFormDataNum;
    }

    /**
     * 获取存储量
     * @param basePackageType 基础套餐类型
     * @return
     */
    private Integer getBaseCapacityNum(Integer basePackageType) {
        Integer baseCapacityNum = 0;
        PackageTypeEnum packageTypeEnum = PackageTypeEnum.getByType(basePackageType);
        switch (packageTypeEnum) {
            case FREE:
                baseCapacityNum = BasePackageConstant.FreePackage.CAPACITY_NUM;
                break;
            case STANDARD:
                baseCapacityNum = BasePackageConstant.StandardPackage.CAPACITY_NUM;
                break;
            case ADVANCED:
                baseCapacityNum = BasePackageConstant.AdvancedPackage.CAPACITY_NUM;
                break;
            case ULTIMATE:
                baseCapacityNum = BasePackageConstant.UltimatePackage.CAPACITY_NUM;
                break;
            default:
                break;
        }
        return baseCapacityNum;
    }


    /**
     * 获取自定义流程数
     * @param basePackageType 基础套餐类型
     * @return
     */
    private Integer getBaseCustomFlowNum(Integer basePackageType) {
        Integer baseCustomFlowNum = 0;
        PackageTypeEnum packageTypeEnum = PackageTypeEnum.getByType(basePackageType);
        switch (packageTypeEnum) {
            case FREE:
                baseCustomFlowNum = BasePackageConstant.FreePackage.CUSTOM_FLOW_NUM;
                break;
            case STANDARD:
                baseCustomFlowNum = BasePackageConstant.StandardPackage.CUSTOM_FLOW_NUM;
                break;
            case ADVANCED:
                baseCustomFlowNum = BasePackageConstant.AdvancedPackage.CUSTOM_FLOW_NUM;
                break;
            case ULTIMATE:
                baseCustomFlowNum = BasePackageConstant.UltimatePackage.CUSTOM_FLOW_NUM;
                break;
            default:
                break;
        }
        return baseCustomFlowNum;
    }

    /**
     * 获取每个应用的智能报表
     * @param basePackageType 基础套餐类型
     * @return
     */
    private Integer getBaseCustomChartNum(Integer basePackageType) {
        Integer baseCustomChartNum = 0;
        PackageTypeEnum packageTypeEnum = PackageTypeEnum.getByType(basePackageType);
        switch (packageTypeEnum) {
            case FREE:
                baseCustomChartNum = BasePackageConstant.FreePackage.CUSTOM_CHART_NUM;
                break;
            case STANDARD:
                baseCustomChartNum = BasePackageConstant.StandardPackage.CUSTOM_CHART_NUM;
                break;
            case ADVANCED:
                baseCustomChartNum = BasePackageConstant.AdvancedPackage.CUSTOM_CHART_NUM;
                break;
            case ULTIMATE:
                baseCustomChartNum = BasePackageConstant.UltimatePackage.CUSTOM_CHART_NUM;
                break;
            default:
                break;
        }
        return baseCustomChartNum;
    }

    /**
     * 获取自定义应用数
     * @param basePackageType 基础套餐类型
     * @return
     */
    private Integer getBaseCustomApplicationNum(Integer basePackageType) {
        Integer baseCustomApplicationNum = 0;
        PackageTypeEnum packageTypeEnum = PackageTypeEnum.getByType(basePackageType);
        switch (packageTypeEnum) {
            case FREE:
                baseCustomApplicationNum = BasePackageConstant.FreePackage.CUSTOM_APPLICATION_NUM;
                break;
            case STANDARD:
                baseCustomApplicationNum = BasePackageConstant.StandardPackage.CUSTOM_APPLICATION_NUM;
                break;
            case ADVANCED:
                baseCustomApplicationNum = BasePackageConstant.AdvancedPackage.CUSTOM_APPLICATION_NUM;
                break;
            case ULTIMATE:
                baseCustomApplicationNum = BasePackageConstant.UltimatePackage.CUSTOM_APPLICATION_NUM;
                break;
            default:
                break;
        }
        return baseCustomApplicationNum;
    }

    /**
     * 获取智能助手
     * @param basePackageType 基础套餐类型
     * @return
     */
    private Integer getBaseSfaNum(Integer basePackageType) {
        Integer baseSfaNum = 0;
        PackageTypeEnum packageTypeEnum = PackageTypeEnum.getByType(basePackageType);
        switch (packageTypeEnum) {
            case FREE:
                baseSfaNum = BasePackageConstant.FreePackage.SFA_NUM;
                break;
            case STANDARD:
                baseSfaNum = BasePackageConstant.StandardPackage.SFA_NUM;
                break;
            case ADVANCED:
                baseSfaNum = BasePackageConstant.AdvancedPackage.SFA_NUM;
                break;
            case ULTIMATE:
                baseSfaNum = BasePackageConstant.UltimatePackage.SFA_NUM;
                break;
            default:
                break;
        }
        return baseSfaNum;
    }

    /**
     * 获取api接口
     * @param basePackageType 基础套餐类型
     * @return
     */
    private Integer getBaseApiNum(Integer basePackageType) {
        Integer baseApiNum = 0;
        PackageTypeEnum packageTypeEnum = PackageTypeEnum.getByType(basePackageType);
        switch (packageTypeEnum) {
            case FREE:
                baseApiNum = BasePackageConstant.FreePackage.API_NUM;
                break;
            case STANDARD:
                baseApiNum = BasePackageConstant.StandardPackage.API_NUM;
                break;
            case ADVANCED:
                baseApiNum = BasePackageConstant.AdvancedPackage.API_NUM;
                break;
            case ULTIMATE:
                baseApiNum = BasePackageConstant.UltimatePackage.API_NUM;
                break;
            default:
                break;
        }
        return baseApiNum;
    }

    /**
     * 获取业务规则
     * @param basePackageType 基础套餐类型
     * @return
     */
    private Integer getBaseBusinessRulesNum(Integer basePackageType) {
        Integer baseApiNum = 0;
        PackageTypeEnum packageTypeEnum = PackageTypeEnum.getByType(basePackageType);
        switch (packageTypeEnum) {
            case FREE:
                baseApiNum = BasePackageConstant.FreePackage.BUSINESS_RULES_NUM;
                break;
            case STANDARD:
                baseApiNum = BasePackageConstant.StandardPackage.BUSINESS_RULES_NUM;
                break;
            case ADVANCED:
                baseApiNum = BasePackageConstant.AdvancedPackage.BUSINESS_RULES_NUM;
                break;
            case ULTIMATE:
                baseApiNum = BasePackageConstant.UltimatePackage.BUSINESS_RULES_NUM;
                break;
            default:
                break;
        }
        return baseApiNum;
    }

    /**
     * 获取业务规则
     * @param basePackageType 基础套餐类型
     * @return
     */
    private Integer getBaseWorkflowNum(Integer basePackageType) {
        Integer baseApiNum = 0;
        PackageTypeEnum packageTypeEnum = PackageTypeEnum.getByType(basePackageType);
        switch (packageTypeEnum) {
            case FREE:
                baseApiNum = BasePackageConstant.FreePackage.WORKFLOW;
                break;
            case STANDARD:
                baseApiNum = BasePackageConstant.StandardPackage.WORKFLOW;
                break;
            case ADVANCED:
                baseApiNum = BasePackageConstant.AdvancedPackage.WORKFLOW;
                break;
            case ULTIMATE:
                baseApiNum = BasePackageConstant.UltimatePackage.WORKFLOW;
                break;
            default:
                break;
        }
        return baseApiNum;
    }

    /**
     * 获取业务规则
     * @param basePackageType 基础套餐类型
     * @return
     */
    private Integer getBaseHomePageNum(Integer basePackageType) {
        Integer baseApiNum = 0;
        PackageTypeEnum packageTypeEnum = PackageTypeEnum.getByType(basePackageType);
        switch (packageTypeEnum) {
            case FREE:
                baseApiNum = BasePackageConstant.FreePackage.HOME_PAGE_NUM;
                break;
            case STANDARD:
                baseApiNum = BasePackageConstant.StandardPackage.HOME_PAGE_NUM;
                break;
            case ADVANCED:
                baseApiNum = BasePackageConstant.AdvancedPackage.HOME_PAGE_NUM;
                break;
            case ULTIMATE:
                baseApiNum = BasePackageConstant.UltimatePackage.HOME_PAGE_NUM;
                break;
            default:
                break;
        }
        return baseApiNum;
    }

    private JSONObject formatValueAdded(ValueAddedTypeEnum valueAddedTypeEnum, Object value){
        JSONObject valueAdded = new JSONObject();
        valueAdded.put("alias", valueAddedTypeEnum.getAlias());
        valueAdded.put("name", valueAddedTypeEnum.getName());
        valueAdded.put("type", valueAddedTypeEnum.getType());
        valueAdded.put("value", value);
        return valueAdded;
    }

    /**
     * 通过数据库配置生成总表单限制存入redis的配置,此配置仅用到primaryNum
     * @param corpid 公司id
     * @param valueAdded {"alias":"totalFormDataNum","name":"总表单数据量", "type":4, "value":5000000}
     * @return {"totalValue":0,"usedValue":0,"status":0 }
     * 创建时间 2019/3/26 4:28 PM
     * 修改时间 2019/3/26 4:28 PM
     * @author chy
     * @since v1.0
     * @version v1.0
     */
    private JSONObject allFormNum4Redis(String corpid, JSONObject valueAdded) throws XbbException {
        Integer saasTableCount = getSaasTableCount(corpid);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        //解析查询条件
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termsQuery("del", Arrays.asList(DelEnum.NORMAL.getDel(), DelEnum.DELETE.getDel())));
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_FORM_DATA.getType()));
        sourceBuilder.query(boolQueryBuilder);
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_FORM_DATA.getIndex());
        searchRequest.source(sourceBuilder);
        long countL = paasFormDataEsModel.count(searchRequest);
        Integer count = Integer.valueOf(String.valueOf(countL)) + saasTableCount;
        Double value = valueAdded.getDouble("value");
        Double totalValueD = value * 10000.0;
        Integer totalValue = totalValueD.intValue();
        Integer status = getPackageStatus(totalValue, count);
        return packageJson(totalValue, count, status);
    }


    /**
     * 通过数据库配置生成单表单限制存入redis的配置,此配置仅用到secondaryNum
     * @param corpid 公司id
     * @param valueAdded {"alias":"oneFormDataNum","name":"单表单数据量", "type":5, "value":5000000}
     * @param xbbRefTypeEnum 指定saas业务的单表数据量时，需要传 参照 {@link com.xbongbong.pro.enums.SaasTableCountTypeEnum}
     * @param formId 自定义表单的单表数据量时，需要传
     * @return {"totalValue":0,"usedValue":0,"status":0 }
     * 创建时间 2019/3/26 4:28 PM
     * 修改时间 2019/3/26 4:28 PM
     * @author chy
     * @since v1.0
     * @version v1.0
     */
    private JSONObject oneFormNum4Redis(String corpid, JSONObject valueAdded, XbbRefTypeEnum xbbRefTypeEnum, Long formId) throws XbbException {
        Integer count = 0;
        if (SaasTableCountTypeEnum.isSaasData(xbbRefTypeEnum)) {
            count = getSaasTableCount(corpid, xbbRefTypeEnum);
        } else {
            count = getPaasDataCount(corpid, formId);
        }
        Double value = valueAdded.getDouble("value");
        Double totalValueD = value * 10000.0;
        Integer totalValue = totalValueD.intValue();
        Integer status = getPackageStatus(totalValue, count);
        return packageJson(totalValue, count, status);
    }

    /**
     * 获取saas业务存于各自表的数据量
     * @param corpid
     * @return
     * 创建时间 2019/7/4 2:01 PM
     * 修改时间 2019/7/4 2:01 PM
     * @author chy
     * @since v1.0
     * @version v1.0
     */
    private Integer getSaasTableCount(String corpid) throws XbbException {
        return getSaasTableCount(corpid, null);
    }

    /**
     * 获取saas业务的数据
     * xbbRefTypeEnum为null时，查所有数据量
     * xbbRefTypeEnum不为null时，查对应业务数据量
     * @param corpid
     * @param xbbRefTypeEnum
     * @return
     * 创建时间 2019/7/4 2:01 PM
     * 修改时间 2019/7/4 2:01 PM
     * @author chy
     * @since v1.0
     * @version v1.0
     */
    private Integer getSaasTableCount(String corpid,  XbbRefTypeEnum xbbRefTypeEnum) throws XbbException {
        Integer saasTableCount = 0;
        Map<Integer, Integer> saasCountMap = null;

        if (Objects.isNull(xbbRefTypeEnum)) {
            saasCountMap = getSaasCountMap(corpid);
        } else {
            saasCountMap = getSaasCountMap(corpid, xbbRefTypeEnum);
        }
        if ( Objects.nonNull(saasCountMap)) {
            Collection<Integer> values = saasCountMap.values();
            for (Integer count : values) {
                saasTableCount += count;
            }
        }
        return saasTableCount;
    }

    private Map<Integer, Integer> getSaasCountMap(String corpid) throws XbbException {
        return getSaasCountMap(corpid, null);
    }

    private Map<Integer, Integer> getSaasCountMap(String corpid,  XbbRefTypeEnum xbbRefTypeEnum) throws XbbException {
        Map<Integer, Integer> saasCountMap = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        param.put("corpid", corpid);
        param.put("del", 0);

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = boolQuery();

        if (Objects.isNull(xbbRefTypeEnum) || Objects.equals(xbbRefTypeEnum, SaasTableCountTypeEnum.ASSEMBLE.getXbbRefTypeEnum())) {
            //解析查询条件
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType())));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_ASSEMBLE.getType()));
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_ASSEMBLE.getIndex());
            searchRequest.source(sourceBuilder);
            long assembleCount = paasFormDataEsModel.count(searchRequest);
            saasCountMap.put(SaasTableCountTypeEnum.ASSEMBLE.getXbbRefTypeEnum().getCode(), Integer.valueOf(String.valueOf(assembleCount)));
        }

        if (Objects.isNull(xbbRefTypeEnum) || Objects.equals(xbbRefTypeEnum, SaasTableCountTypeEnum.BOM_BILL.getXbbRefTypeEnum())) {
            //解析查询条件
            boolQueryBuilder.filter().clear();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType())));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_BOM.getType()));
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_BOM.getIndex());
            searchRequest.source(sourceBuilder);
            long bomCount = paasFormDataEsModel.count(searchRequest);
            saasCountMap.put(SaasTableCountTypeEnum.BOM_BILL.getXbbRefTypeEnum().getCode(), Integer.valueOf(String.valueOf(bomCount)));
        }

        if (Objects.isNull(xbbRefTypeEnum) || Objects.equals(xbbRefTypeEnum, SaasTableCountTypeEnum.COMMUNICATE_PLAN.getXbbRefTypeEnum())) {
            //解析查询条件
            boolQueryBuilder.filter().clear();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_COMMUNICATE_PLAN.getType()));
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_COMMUNICATE_PLAN.getIndex());
            searchRequest.source(sourceBuilder);
            long communicatePlanCount = paasFormDataEsModel.count(searchRequest);
            saasCountMap.put(SaasTableCountTypeEnum.COMMUNICATE_PLAN.getXbbRefTypeEnum().getCode(), Integer.valueOf(String.valueOf(communicatePlanCount)));
        }

        if (Objects.isNull(xbbRefTypeEnum) || Objects.equals(xbbRefTypeEnum, SaasTableCountTypeEnum.QUOTATION.getXbbRefTypeEnum())) {
            //解析查询条件
            boolQueryBuilder.filter().clear();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType())));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_QUOTATION.getType()));
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_QUOTATION.getIndex());
            searchRequest.source(sourceBuilder);
            long quotationCount = paasFormDataEsModel.count(searchRequest);
            saasCountMap.put(SaasTableCountTypeEnum.QUOTATION.getXbbRefTypeEnum().getCode(), Integer.valueOf(String.valueOf(quotationCount)));
        }

        if (Objects.isNull(xbbRefTypeEnum) || Objects.equals(xbbRefTypeEnum, SaasTableCountTypeEnum.CONTACT.getXbbRefTypeEnum())) {
            //解析查询条件
            boolQueryBuilder.filter().clear();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType())));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_CONTACT.getType()));
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_CONTACT.getIndex());
            searchRequest.source(sourceBuilder);
            long contactCount = paasFormDataEsModel.count(searchRequest);
            saasCountMap.put(SaasTableCountTypeEnum.CONTACT.getXbbRefTypeEnum().getCode(), Integer.valueOf(String.valueOf(contactCount)));
        }

        if (Objects.isNull(xbbRefTypeEnum) || Objects.equals(xbbRefTypeEnum, SaasTableCountTypeEnum.CONTRACT.getXbbRefTypeEnum())) {
            //解析查询条件
            boolQueryBuilder.filter().clear();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType())));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_CONTRACT.getType()));
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_CONTRACT.getIndex());
            searchRequest.source(sourceBuilder);
            long contractCount = paasFormDataEsModel.count(searchRequest);
            saasCountMap.put(SaasTableCountTypeEnum.CONTRACT.getXbbRefTypeEnum().getCode(), Integer.valueOf(String.valueOf(contractCount)));
        }

        if (Objects.isNull(xbbRefTypeEnum) || Objects.equals(xbbRefTypeEnum, SaasTableCountTypeEnum.CUSTOMER.getXbbRefTypeEnum())) {
            //解析查询条件
            boolQueryBuilder.filter().clear();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termsQuery("del", Arrays.asList(DelEnum.NORMAL.getDel(), DelEnum.DELETE.getDel())));
            boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType())));
            IndexTypeEnum customerIndex = indexTypeModel.getCustomerIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,customerIndex.getType()));
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(customerIndex.getIndex());
            searchRequest.source(sourceBuilder);
            long customerCount = paasFormDataEsModel.count(searchRequest);
            saasCountMap.put(SaasTableCountTypeEnum.CUSTOMER.getXbbRefTypeEnum().getCode(), Integer.valueOf(String.valueOf(customerCount)));
        }

        if (Objects.isNull(xbbRefTypeEnum) || Objects.equals(xbbRefTypeEnum, SaasTableCountTypeEnum.CUSTOMER_COMMUNICATE.getXbbRefTypeEnum())) {
            sourceBuilder = new SearchSourceBuilder();
            boolQueryBuilder = boolQuery();
            //解析查询条件
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termQuery(FieldTypeEnum.LOG_TYPE.getAlias(),0));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE.getType()));
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE.getIndex());
            searchRequest.source(sourceBuilder);
            long customerCommunicateCount = paasFormDataEsModel.count(searchRequest);
            saasCountMap.put(SaasTableCountTypeEnum.CUSTOMER_COMMUNICATE.getXbbRefTypeEnum().getCode(), Integer.valueOf(String.valueOf(customerCommunicateCount)));
        }

        if (Objects.isNull(xbbRefTypeEnum) || Objects.equals(xbbRefTypeEnum, SaasTableCountTypeEnum.INSTOCK.getXbbRefTypeEnum())) {
            //解析查询条件
            boolQueryBuilder.filter().clear();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType())));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_INSTOCK.getType()));
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_INSTOCK.getIndex());
            searchRequest.source(sourceBuilder);
            long instockCount = paasFormDataEsModel.count(searchRequest);
            saasCountMap.put(SaasTableCountTypeEnum.INSTOCK.getXbbRefTypeEnum().getCode(), Integer.valueOf(String.valueOf(instockCount)));
        }

        if (Objects.isNull(xbbRefTypeEnum) || Objects.equals(xbbRefTypeEnum, SaasTableCountTypeEnum.INVENTORY.getXbbRefTypeEnum())) {
            //解析查询条件
            boolQueryBuilder.filter().clear();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType())));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_INVENTORY.getType()));
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_INVENTORY.getIndex());
            searchRequest.source(sourceBuilder);
            long inventoryCount = paasFormDataEsModel.count(searchRequest);
            saasCountMap.put(SaasTableCountTypeEnum.INVENTORY.getXbbRefTypeEnum().getCode(), Integer.valueOf(String.valueOf(inventoryCount)));
        }

        if (Objects.isNull(xbbRefTypeEnum) || Objects.equals(xbbRefTypeEnum, SaasTableCountTypeEnum.SALES_OPPORTUNITY.getXbbRefTypeEnum())) {
            //解析查询条件
            boolQueryBuilder.filter().clear();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType())));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_OPPORTUNITY.getType()));
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_OPPORTUNITY.getIndex());
            searchRequest.source(sourceBuilder);
            long opportunityCount = paasFormDataEsModel.count(searchRequest);
            saasCountMap.put(SaasTableCountTypeEnum.SALES_OPPORTUNITY.getXbbRefTypeEnum().getCode(), Integer.valueOf(String.valueOf(opportunityCount)));
        }

        if (Objects.isNull(xbbRefTypeEnum) || Objects.equals(xbbRefTypeEnum, SaasTableCountTypeEnum.OUTSTOCK.getXbbRefTypeEnum())) {
            //解析查询条件
            boolQueryBuilder.filter().clear();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType())));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_OUTSTOCK.getType()));
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_OUTSTOCK.getIndex());
            searchRequest.source(sourceBuilder);
            long outstockCount = paasFormDataEsModel.count(searchRequest);
            saasCountMap.put(SaasTableCountTypeEnum.OUTSTOCK.getXbbRefTypeEnum().getCode(), Integer.valueOf(String.valueOf(outstockCount)));
        }

        if (Objects.isNull(xbbRefTypeEnum) || Objects.equals(xbbRefTypeEnum, SaasTableCountTypeEnum.PAY_PLAN.getXbbRefTypeEnum())) {
            //解析查询条件
            boolQueryBuilder.filter().clear();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_PAY_PLAN.getType()));
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_PAY_PLAN.getIndex());
            searchRequest.source(sourceBuilder);
            long payPlanCount = paasFormDataEsModel.count(searchRequest);
            saasCountMap.put(SaasTableCountTypeEnum.PAY_PLAN.getXbbRefTypeEnum().getCode(), Integer.valueOf(String.valueOf(payPlanCount)));
        }

        if (Objects.isNull(xbbRefTypeEnum) || Objects.equals(xbbRefTypeEnum, SaasTableCountTypeEnum.PAY_SHEET.getXbbRefTypeEnum())) {
            //解析查询条件
            boolQueryBuilder.filter().clear();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType())));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET.getType()));
            //只要无子和父的
            boolQueryBuilder.filter(termsQuery(BasicConstant.ALONE, SheetAloneEnum.getNotChildCodeList()));
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET.getIndex());
            searchRequest.source(sourceBuilder);
            long paySheetCount = paasFormDataEsModel.count(searchRequest);
            saasCountMap.put(SaasTableCountTypeEnum.PAY_SHEET.getXbbRefTypeEnum().getCode(), Integer.valueOf(String.valueOf(paySheetCount)));
        }

        if (Objects.isNull(xbbRefTypeEnum) || Objects.equals(xbbRefTypeEnum, SaasTableCountTypeEnum.PAYMENT.getXbbRefTypeEnum())) {
            //解析查询条件
            boolQueryBuilder.filter().clear();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            boolQueryBuilder.mustNot(termQuery(PaymentEnum.getEsAttr4Keyword(PaymentEnum.IS_RED), 1));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_PAYMENT.getType()));
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_PAYMENT.getIndex());
            searchRequest.source(sourceBuilder);
            long paymentCount = paasFormDataEsModel.count(searchRequest);
            saasCountMap.put(SaasTableCountTypeEnum.PAYMENT.getXbbRefTypeEnum().getCode(), Integer.valueOf(String.valueOf(paymentCount)));
        }

        if (Objects.isNull(xbbRefTypeEnum) || Objects.equals(xbbRefTypeEnum, SaasTableCountTypeEnum.PAYMENT_SHEET.getXbbRefTypeEnum())) {
            //解析查询条件
            boolQueryBuilder.filter().clear();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            //只要无子和父的
            boolQueryBuilder.filter(termsQuery(BasicConstant.ALONE, SheetAloneEnum.getNotChildCodeList()));
            boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType())));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET.getType()));
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET.getIndex());
            searchRequest.source(sourceBuilder);
            long paymentSheetCount = paasFormDataEsModel.count(searchRequest);
            saasCountMap.put(SaasTableCountTypeEnum.PAYMENT_SHEET.getXbbRefTypeEnum().getCode(), Integer.valueOf(String.valueOf(paymentSheetCount)));
        }

        if (Objects.isNull(xbbRefTypeEnum) || Objects.equals(xbbRefTypeEnum, SaasTableCountTypeEnum.PRODUCT.getXbbRefTypeEnum())) {
            //解析查询条件
            boolQueryBuilder.filter().clear();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            //算sku的
            boolQueryBuilder.mustNot(termQuery(ProductEnum.getAttrConnectData(ProductEnum.PARENT_ID), 0));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_PRODUCT.getType()));
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_PRODUCT.getIndex());
            searchRequest.source(sourceBuilder);
            long productCount = paasFormDataEsModel.count(searchRequest);
            saasCountMap.put(SaasTableCountTypeEnum.PRODUCT.getXbbRefTypeEnum().getCode(), Integer.valueOf(String.valueOf(productCount)));
        }

        if (Objects.isNull(xbbRefTypeEnum) || Objects.equals(xbbRefTypeEnum, SaasTableCountTypeEnum.PRODUCTION_ORDER.getXbbRefTypeEnum())) {
            //解析查询条件
            boolQueryBuilder.filter().clear();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType())));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_PRODUCTION_ORDER.getType()));
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_PRODUCTION_ORDER.getIndex());
            searchRequest.source(sourceBuilder);
            long productionOrderCount = paasFormDataEsModel.count(searchRequest);
            saasCountMap.put(SaasTableCountTypeEnum.PRODUCTION_ORDER.getXbbRefTypeEnum().getCode(), Integer.valueOf(String.valueOf(productionOrderCount)));
        }

        if (Objects.isNull(xbbRefTypeEnum) || Objects.equals(xbbRefTypeEnum, SaasTableCountTypeEnum.PURCHASE.getXbbRefTypeEnum())) {
            //解析查询条件
            boolQueryBuilder.filter().clear();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType())));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_PURCHASE.getType()));
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_PURCHASE.getIndex());
            searchRequest.source(sourceBuilder);
            long purchaseCount = paasFormDataEsModel.count(searchRequest);
            saasCountMap.put(SaasTableCountTypeEnum.PURCHASE.getXbbRefTypeEnum().getCode(), Integer.valueOf(String.valueOf(purchaseCount)));
        }

        if (Objects.isNull(xbbRefTypeEnum) || Objects.equals(xbbRefTypeEnum, SaasTableCountTypeEnum.REFUND.getXbbRefTypeEnum())) {
            //解析查询条件
            boolQueryBuilder.filter().clear();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType())));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_REFUND.getType()));
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_REFUND.getIndex());
            searchRequest.source(sourceBuilder);
            long refundCount = paasFormDataEsModel.count(searchRequest);
            saasCountMap.put(SaasTableCountTypeEnum.REFUND.getXbbRefTypeEnum().getCode(), Integer.valueOf(String.valueOf(refundCount)));
        }

        if (Objects.isNull(xbbRefTypeEnum) || Objects.equals(xbbRefTypeEnum, SaasTableCountTypeEnum.RETURNED_PURCHASE.getXbbRefTypeEnum())) {
            //解析查询条件
            boolQueryBuilder.filter().clear();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType())));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_RETURNED_PURCHASE.getType()));
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_RETURNED_PURCHASE.getIndex());
            searchRequest.source(sourceBuilder);
            long returnedPurchaseCount = paasFormDataEsModel.count(searchRequest);
            saasCountMap.put(SaasTableCountTypeEnum.RETURNED_PURCHASE.getXbbRefTypeEnum().getCode(), Integer.valueOf(String.valueOf(returnedPurchaseCount)));
        }

        if (Objects.isNull(xbbRefTypeEnum) || Objects.equals(xbbRefTypeEnum, SaasTableCountTypeEnum.SUPPLIER.getXbbRefTypeEnum())) {
            //解析查询条件
            boolQueryBuilder.filter().clear();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType())));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_SUPPLIER.getType()));
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_SUPPLIER.getIndex());
            searchRequest.source(sourceBuilder);
            long supplierCount = paasFormDataEsModel.count(searchRequest);
            saasCountMap.put(SaasTableCountTypeEnum.SUPPLIER.getXbbRefTypeEnum().getCode(), Integer.valueOf(String.valueOf(supplierCount)));
        }

        if (Objects.isNull(xbbRefTypeEnum) || Objects.equals(xbbRefTypeEnum, SaasTableCountTypeEnum.SUPPLIER_COMMUNICATE.getXbbRefTypeEnum())) {
            //解析查询条件
            boolQueryBuilder.filter().clear();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_SUPPLIER_COMMUNICATE.getType()));
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_SUPPLIER_COMMUNICATE.getIndex());
            searchRequest.source(sourceBuilder);
            long supplierCommunicateCount = paasFormDataEsModel.count(searchRequest);
            saasCountMap.put(SaasTableCountTypeEnum.SUPPLIER_COMMUNICATE.getXbbRefTypeEnum().getCode(), Integer.valueOf(String.valueOf(supplierCommunicateCount)));
        }

        if (Objects.isNull(xbbRefTypeEnum) || Objects.equals(xbbRefTypeEnum, SaasTableCountTypeEnum.SUPPLIER_CONTACT.getXbbRefTypeEnum())) {
            //解析查询条件
            boolQueryBuilder.filter().clear();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType())));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT.getType()));
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT.getIndex());
            searchRequest.source(sourceBuilder);
            long supplierContactCount = paasFormDataEsModel.count(searchRequest);
            saasCountMap.put(SaasTableCountTypeEnum.SUPPLIER_CONTACT.getXbbRefTypeEnum().getCode(), Integer.valueOf(String.valueOf(supplierContactCount)));
        }

        if (Objects.isNull(xbbRefTypeEnum) || Objects.equals(xbbRefTypeEnum, SaasTableCountTypeEnum.TRANSFER.getXbbRefTypeEnum())) {
            //解析查询条件
            boolQueryBuilder.filter().clear();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType())));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_TRANSFER.getType()));
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_TRANSFER.getIndex());
            searchRequest.source(sourceBuilder);
            long transferCount = paasFormDataEsModel.count(searchRequest);
            saasCountMap.put(SaasTableCountTypeEnum.TRANSFER.getXbbRefTypeEnum().getCode(), Integer.valueOf(String.valueOf(transferCount)));
        }

        if (Objects.isNull(xbbRefTypeEnum) || Objects.equals(xbbRefTypeEnum, SaasTableCountTypeEnum.WORK_ORDER.getXbbRefTypeEnum())) {
            //解析查询条件
            boolQueryBuilder.filter().clear();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType())));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_WORK_ORDER.getType()));
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_WORK_ORDER.getIndex());
            searchRequest.source(sourceBuilder);
            long workOrderDataCount = paasFormDataEsModel.count(searchRequest);
            saasCountMap.put(SaasTableCountTypeEnum.WORK_ORDER.getXbbRefTypeEnum().getCode(), Integer.valueOf(String.valueOf(workOrderDataCount)));
        }

        if (Objects.isNull(xbbRefTypeEnum) || Objects.equals(xbbRefTypeEnum, SaasTableCountTypeEnum.WORK_REPORT.getXbbRefTypeEnum())) {
            //解析查询条件
            boolQueryBuilder.filter().clear();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_WORK_REPORT.getType()));
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_WORK_REPORT.getIndex());
            searchRequest.source(sourceBuilder);
            long workReportCount = paasFormDataEsModel.count(searchRequest);
            saasCountMap.put(SaasTableCountTypeEnum.WORK_REPORT.getXbbRefTypeEnum().getCode(), Integer.valueOf(String.valueOf(workReportCount)));
        }

        if (Objects.isNull(xbbRefTypeEnum) || Objects.equals(xbbRefTypeEnum, SaasTableCountTypeEnum.INVOICE.getXbbRefTypeEnum())) {
            //解析查询条件
            boolQueryBuilder.filter().clear();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType())));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_INVOICE.getType()));
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_INVOICE.getIndex());
            searchRequest.source(sourceBuilder);
            long invoiceCount = paasFormDataEsModel.count(searchRequest);
            saasCountMap.put(SaasTableCountTypeEnum.INVOICE.getXbbRefTypeEnum().getCode(), Integer.valueOf(String.valueOf(invoiceCount)));
        }

        if (Objects.isNull(xbbRefTypeEnum) || Objects.equals(xbbRefTypeEnum, SaasTableCountTypeEnum.PURCHASE_INVOICE.getXbbRefTypeEnum())) {
            //解析查询条件
            boolQueryBuilder.filter().clear();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType())));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE.getType()));
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE.getIndex());
            searchRequest.source(sourceBuilder);
            long purchaseInvoiceCount = paasFormDataEsModel.count(searchRequest);
            saasCountMap.put(SaasTableCountTypeEnum.PURCHASE_INVOICE.getXbbRefTypeEnum().getCode(), Integer.valueOf(String.valueOf(purchaseInvoiceCount)));
        }

        if (Objects.isNull(xbbRefTypeEnum) || Objects.equals(xbbRefTypeEnum, SaasTableCountTypeEnum.CLUE.getXbbRefTypeEnum())) {
            //解析查询条件
            boolQueryBuilder.filter().clear();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType())));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_CLUE.getType()));
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_CLUE.getIndex());
            searchRequest.source(sourceBuilder);
            long clueCount = paasFormDataEsModel.count(searchRequest);
            saasCountMap.put(SaasTableCountTypeEnum.CLUE.getXbbRefTypeEnum().getCode(), Integer.valueOf(String.valueOf(clueCount)));
        }

        if (Objects.isNull(xbbRefTypeEnum) || Objects.equals(xbbRefTypeEnum, SaasTableCountTypeEnum.KNOWLEDGE_BASE.getXbbRefTypeEnum())) {
            //解析查询条件
            boolQueryBuilder.filter().clear();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_KNOWLEDGE_DATA.getType()));
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_KNOWLEDGE_DATA.getIndex());
            searchRequest.source(sourceBuilder);
            long knowledgeCount = paasFormDataEsModel.count(searchRequest);
            saasCountMap.put(SaasTableCountTypeEnum.KNOWLEDGE_BASE.getXbbRefTypeEnum().getCode(), Integer.valueOf(String.valueOf(knowledgeCount)));
        }

        return saasCountMap;
    }
    /**
     * 存于redis的jsonObject
     * @param totalValue 套餐量
     * @param usedValue 已使用量
     * @param status 状态
     * @return {"totalValue":2, "usedValue":1, "status":1}
     * 创建时间 2019/3/27 10:31 AM
     * 修改时间 2019/3/27 10:31 AM
     * @author chy
     * @since v1.0
     * @version v1.0
     */
    public JSONObject packageJson(Integer totalValue, Integer usedValue, Integer status) {
        JSONObject packageJson = new JSONObject();
        packageJson.put("totalValue", totalValue);
        packageJson.put("usedValue", usedValue);
        packageJson.put("status", status);
        return packageJson;
    }
    private Integer getPaasDataCount(String corpid, Long formId) throws XbbException {
        if (Objects.isNull(formId)) {
            return BasicConstant.ZERO;
        }
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        //解析查询条件
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termsQuery("del", Arrays.asList(DelEnum.NORMAL.getDel(), DelEnum.DELETE.getDel())));
        boolQueryBuilder.filter(termQuery("formId", formId));
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_FORM_DATA.getType()));
        sourceBuilder.query(boolQueryBuilder);
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_FORM_DATA.getIndex());
        searchRequest.source(sourceBuilder);
        long count = paasFormDataEsModel.count(searchRequest);
        return Integer.valueOf(String.valueOf(count));
    }
    /**
     * 获取套餐状态 参考{@link PackageStatusEnum}
     * @param totalValue
     * @param usedValue
     * @return
     */
    public Integer getPackageStatus(Integer totalValue, Integer usedValue) {

        if (Objects.equals(totalValue, BasicConstant.ZERO)) {
            return PackageStatusEnum.UNAVAILABLE.getCode();
        }

        Float rate = usedValue.floatValue()/totalValue.floatValue();

        if (PackageStatusEnum.NORMAL.getLowRate() <= rate && rate <= PackageStatusEnum.NORMAL.getHighRate()) {
            return PackageStatusEnum.NORMAL.getCode();
        }

        if (PackageStatusEnum.WARNING.getLowRate() < rate && rate < PackageStatusEnum.WARNING.getHighRate()) {
            return PackageStatusEnum.WARNING.getCode();
        }

        if (PackageStatusEnum.OVER.getLowRate() < rate) {
            return PackageStatusEnum.OVER.getCode();
        }

        return PackageStatusEnum.UNAVAILABLE.getCode();
    }

    /**
     * 通过数据库配置生成总表单限制存入redis的配置,此配置仅用到primaryNum
     * @param corpid 公司id
     * @param valueAdded {"alias":"sfaNum","name":"数据集", "type":29, "value":20}
     * @return {"totalValue":0,"usedValue":0,"status":0 }
     * @author zcp
     * @since v1.0
     * @version v1.0
     */
    private JSONObject dataSetNum4Redis(String corpid, JSONObject valueAdded){
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("del", 0);
        Integer count = dataSetModel.getEntitysCount(param);

        Integer totalValue = valueAdded.getInteger("value");
        Integer status = getPackageStatus(totalValue, count);

        return packageJson(totalValue, count, status);
    }
    /**
     * 数据集数量
     * @param basePackageType
     * @return java.lang.Integer
     * @author zcp
     * @since v1.0
     * @version v1.0
     */
    private Integer getBaseDataSetNum(Integer basePackageType) {
        Integer baseApiNum = 0;
        PackageTypeEnum packageTypeEnum = PackageTypeEnum.getByType(basePackageType);
        switch (packageTypeEnum) {
            case FREE:
                baseApiNum = BasePackageConstant.FreePackage.DATA_SET_NUM;
                break;
            case STANDARD:
                baseApiNum = BasePackageConstant.StandardPackage.DATA_SET_NUM;
                break;
            case ADVANCED:
                baseApiNum = BasePackageConstant.AdvancedPackage.DATA_SET_NUM;
                break;
            case ULTIMATE:
                baseApiNum = BasePackageConstant.UltimatePackage.DATA_SET_NUM;
                break;
            default:
                break;
        }
        return baseApiNum;
    }
}
